<template>
  <a-modal
    v-model:visible="visible"
    title-align="start"
    width="800px"
    :title="formModel.userId? '详细': '新增'"
    :mask-closable=false
    :ok-loading=true
    :draggable=true
  >
    <a-scrollbar style="max-height:600px; overflow: auto;">
      <a-form
        id="addForm"
        ref="formModelRef"
        label-align="left"
        layout="vertical"
        :label-col-props=labelColProps
        :wrapper-col-props=wrapperColProps
        :model="formModel"
        :rules="rules"
      >
        <a-row justify="space-between">
          <a-col :span="11">
            <a-form-item field="loginName" label="登录名">
              <a-input
                v-model="formModel.loginName"
                placeholder="请输入登录名"
                max-length="30"
                show-word-limit
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="userName" label="用户名">
              <a-input
                v-model="formModel.userName"
                placeholder="请输入用户名"
                max-length="10"
                show-word-limit
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="email" label="邮箱">
              <a-input
                v-model="formModel.email"
                placeholder="请输入邮箱"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="phone" label="手机号">
              <a-input
                v-model="formModel.phone"
                placeholder="请输入手机号"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="deptId" label="部门">
              <a-tree-select
                v-model="formModel.deptId"
                placeholder="请选择部门"
                popup-container="#addForm"
                :field-names="fieldNames"
                :data="deptList"
              >
                <template #tree-slot-icon>
                  <icon-folder />
                </template>
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="postIds" label="职位">
              <a-select
                v-model="formModel.postIds"
                placeholder="请选择职位"
                multiple
              >
                <a-option
                  v-for="item of postList"
                  :key="item.postId"
                  :value="item.postId"
                  :tag-props="{color: 'blue'}"
                >
                  {{ item.postName }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="roleIds" label="角色">
              <a-select
                v-model="formModel.roleIds"
                placeholder="请选择角色"
                multiple
              >
                <a-option
                  v-for="item of roleList"
                  :key="item.roleId"
                  :value="item.roleId"
                  :tag-props="{color: 'blue'}"
                >
                  {{ item.roleName }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="sex" label="用户性别">
              <a-radio-group v-model="formModel.sex">
                <a-radio value="0">男</a-radio>
                <a-radio value="1">女</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="status" label="用户状态">
              <a-switch
                v-model="formModel.status"
                type="round"
                :checked-value="'0'"
                :unchecked-value="'1'"
              >
                <template #checked>正常</template>
                <template #unchecked>冻结</template>
              </a-switch>
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item field="visible" label="用户类型">
              <a-switch
                v-model="formModel.userType"
                type="round"
                :checked-value="'0'"
                :unchecked-value="'1'"
              >
                <template #checked>注册用户</template>
                <template #unchecked>系统用户</template>
              </a-switch>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-scrollbar>

    <!-- 底部操作列 -->
    <template #footer>
      <a-button-group>
        <a-button :disabled="loading" @click="cancel">
          取消
        </a-button>
        <a-button
          type="primary"
          :loading="loading"
          :disabled="hasUpdatePermission"
          @click="submit"
        >
          确定
        </a-button>
      </a-button-group>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, defineEmits, defineExpose, computed } from 'vue';
import { addUser, updateUser, detailUser, SysUser } from '@/api/system/user';
import { roleSelect } from '@/api/system/role';
import { postSelect } from '@/api/system/post';
import { deptTree } from '@/api/system/dept';
import { hasPermission } from '@/utils/permission';
import { Message, ValidatedError } from '@arco-design/web-vue';
import { labelColProps, wrapperColProps } from '@/components/dialog-add/config';
import { permission, rules } from '@/views/system/user/config';
import useLoading from '@/hooks/loading';

const emits = defineEmits(['submit']);

const fieldNames = ref({
  key: 'deptId',
  title: 'deptName',
  children: 'children'
});

const { loading, setLoading } = useLoading(false);

const formModelRef = ref();

const visible = ref<boolean>(false);

const formDisable = ref<boolean>(false);

const formModel = ref<SysUser>({});

const roleList = ref();

const postList = ref();

const deptList = ref();

const hasUpdatePermission = computed(() => {
  return formModel.value.userId && !hasPermission([permission.PERMISSION_UPDATE]);
});

const submit = async () => {
  formModelRef.value.validate((errors: undefined | Record<string, ValidatedError>) => {
    if (errors) {
      return;
    }
    setLoading(true);
    if (formModel.value.userId) {
      updateUser(formModel.value).then(() => {
        submitSuccess();
      }).finally(() => {
        setLoading(false);
      });
      return;
    }
    addUser(formModel.value).then(() => {
      submitSuccess();
    }).finally(() => {
      setLoading(false);
    });
  });
};

const submitSuccess = () => {
  cancel();
  emits('submit');
  Message.success('操作成功');
};

const open = async (record: any, disable: boolean) => {
  visible.value = true;
  const roleResp = await roleSelect();
  roleList.value = roleResp.data;
  const postResp = await postSelect();
  postList.value = postResp.data;
  const deptResp = await deptTree(false);
  deptList.value = deptResp.data;
  if (record && record.userId) {
    const { data } = await detailUser(record.userId);
    formModel.value = data;
  } else {
    formModel.value = { userType: '0', status: '0' };
  }
  formDisable.value = disable;
  formModelRef.value.clearValidate();
  setLoading(false);
};

const cancel = () => {
  visible.value = false;
};

defineExpose({
  open
});
</script>

<script lang="ts">
export default {
  name: 'UserDialogAdd'
};
</script>

<style scoped lang="less">

</style>